package zuk.clipvietfun;

import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

public class ApiYoutube extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, OnEditorActionListener {
	private YouTubePlayerView ytpv;
	String title;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.youtube);
		AdView adView = (AdView)findViewById(R.id.adView_youtube);
		adView.loadAd(new AdRequest());
		ytpv = (YouTubePlayerView) findViewById(R.id.youtubeplayer);
		//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		//		ytpv.initialize("AIzaSyC_4OmQ6fX8kObeviR1jKYv-ugpJePx4QE", this);
		ytpv.initialize("AIzaSyBEu5A-veKthrsdzhuf1DvY32vwcpxoJOA", this);
		Bundle extras = getIntent().getExtras();
		title = extras.getString("key");

	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		return false;
	}

	@Override
	public void onInitializationFailure(Provider arg0,YouTubeInitializationResult errorReason) {
		String packageName = "com.google.android.youtube";
		boolean isYoutubeInstalled = isAppInstalled(packageName);
		Toast.makeText(this, "Initialization Fail, Update latest version of Youtube!!", Toast.LENGTH_LONG).show();
		
		if(isYoutubeInstalled){
			startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("vnd.youtube://" + title)));
		}else {
			startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.youtube.com/watch?v=" + title)));
		}
		
		this.finish();
	}

	@Override
	public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1,boolean arg2) {
		if (!arg2) {
			arg1.loadVideo(title);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	@Override
	public void onContentChanged() {
		super.onContentChanged();
	}
	
	protected boolean isAppInstalled(String packageName) {
        Intent mIntent = getPackageManager().getLaunchIntentForPackage(packageName);
        if (mIntent != null) {
            return true;
        }
        else {
            return false;
        }
    }
}
